<template>
  <el-drawer
    v-model="visible"
    title="用户信息"
    direction="rtl"
    size="400px"
    :with-header="true"
    @close="$emit('update:visible', false)"
    :close-on-click-modal="true"
  >
    <el-card class="user-card">
      <div class="user-header">
        <el-avatar :src="user.avatar" size="large" />
        <div class="user-basic">
          <div class="user-name" title="用户名">{{ user.name }}</div>
          <!-- <div class="user-role">{{ user.role }}</div> -->
          <div class="user-email">{{ user.email }}</div>
          <div class="user-points">积分：{{ user.points }}</div>
        </div>
        <div class="edit-btn-box">
          <el-button
            class="edit-btn-inline"
            type="primary"
            size="small"
            @click="editVisible = true"
          >编辑</el-button
          >
          <el-button
            class="edit-btn-inline"
            type="primary"
            size="small"
            :disabled="user.today_is_sign"
            @click="changeCheckIn"
          >{{ user.today_is_sign ? "已签到" : "签到" }}</el-button
          >
        </div>
      </div>
      <el-divider />
      <div class="user-profile">
        <div><strong>公司：</strong>{{ user.profile?.company }}</div>
        <div><strong>位置：</strong>{{ user.profile?.location }}</div>
        <div><strong>个人简介：</strong>{{ user.profile?.bio }}</div>
        <div>
          <strong>个人网站：</strong>
          <a :href="user.profile?.website" target="_blank">{{ user.profile?.website }}</a>
        </div>
      </div>
      <el-divider />
      <div class="user-stat">
        <el-row :gutter="5">
          <el-col :span="12"
          ><div><strong>文章数：</strong>{{ user.stat?.article_count }}</div></el-col
          >
          <el-col :span="12"
          ><div><strong>粉丝数：</strong>{{ user.stat?.follower_count }}</div></el-col
          >
          <el-col :span="12"
          ><div><strong>关注数：</strong>{{ user.stat?.following_count }}</div></el-col
          >
          <el-col :span="12"
          ><div><strong>总浏览：</strong>{{ user.stat?.total_views }}</div></el-col
          >
        </el-row>
      </div>
      <Calendar :listArray="calendarList" ref="calendarRef" />
    </el-card>
    <edit-user-info
      :visible="editVisible"
      :user="user"
      v-if="editVisible"
      @update:visible="editVisible = $event"
    />
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, provide } from '@vue/runtime-core';
import * as authApi from '@/api/auth';
import { useUserStore } from '@/stores/user';
import EditUserInfo from './editUserInfo.vue';
import Calendar from '../common/calendar.vue';
import { ElMessage } from 'element-plus';

const userStore = useUserStore();

const visible = ref(false);
const calendarRef = ref(null);
const calendarList = ref();
const editVisible = ref(false);
const user = ref({
  id: 0,
  name: '',
  avatar: '',
  email: '',
  role: '',
  points: 0,
  today_is_sign: false,
  profile: {
    company: '',
    bio: '',
    location: '',
    website: ''
  },
  stat: {
    article_count: 0,
    follower_count: 0,
    following_count: 0,
    total_views: 0
  }
});

// watch(() => props.visible, (val) => {
//   visible.value = val
// })

/** 打开弹窗 */
const open = async() => {
  visible.value = true;
  getUser();
  fetchCheckInStatus(new Date().getFullYear(), new Date().getMonth() + 1);
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

// 用户签到
const changeCheckIn = async() => {
  try {
    const res = await authApi.userSignin();
    user.value.today_is_sign = true;
    user.value.points += res.data.points || 0;
    ElMessage.success('签到成功');
    fetchCheckInStatus(new Date().getFullYear(), new Date().getMonth() + 1);
  } catch (error) {
    console.log(error);
  }
};
// 获取用户的签到状态与数据
const fetchCheckInStatus = async(year: number, month: number) => {
  try {
    const res = await authApi.userSigninStatus({ month: `${year}-${month}` });

    calendarList.value = res.data.month_data || [];
  } catch (error) {
    console.log(error);
  }
};

// 获取用户信息
const getUser = async() => {
  try {
    const res = await authApi.getUserInfo();
    if (res && res.data) {
      user.value = res.data;
      userStore.user = res.data;
      localStorage.setItem('userInfo', JSON.stringify(res.data));
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 更新信息
provide('fetchCheckInStatus', fetchCheckInStatus);
provide('getUser', getUser);
</script>

<style scoped lang="scss">
.user-card {
  position: relative;
  .user-header {
    display: flex;
    align-items: center;
    .el-avatar {
      flex-shrink: 0;
    }
    .user-basic {
      margin-left: 10px;
      font-size: 14px;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
      min-width: 0;
      .user-name,
      .user-role,
      .user-points .user-email {
        text-align: left;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        width: 100%;
      }
      .user-name {
        font-size: 16px;
        font-weight: bold;
      }
      .user-role {
        color: #409eff;
        margin-top: 2px;
      }
      .user-email {
        color: #888;
        margin-top: 2px;
      }
      .user-points {
        margin-top: 2px;
        color: #999;
      }
    }
    .edit-btn-box {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .edit-btn-inline {
        margin-left: 10px;
        align-self: flex-start;
        margin-bottom: 20px;
      }
    }
  }
  .user-profile {
    margin: 16px 0;
    div {
      margin-bottom: 6px;
      font-size: 14px;
      strong {
        font-size: 14px;
        font-weight: normal;
      }
    }
    a {
      color: #409eff;
      text-decoration: underline;
      font-size: 14px;
    }
    text-align: left;
  }
  .user-stat {
    margin-top: 16px;
    padding-bottom: 20px;
    border-bottom: 1px solid #f0f0f0;
    .el-col {
      text-align: center;
      font-size: 20px;
    }
  }
}
</style>
